﻿using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Management;
using System.Printing;
using TemplatesPrint.DTO;

namespace TemplatesPrint.Tools
{
    public class PrinterTool
    {
        public static List<PrinterDto> GetAllPrinter()
        {
            List<PrinterDto> printerEntities = new List<PrinterDto>();

            PrintDocument fPrintDocument = new PrintDocument();
            string defaultPrinter = fPrintDocument.PrinterSettings.PrinterName;//默认打印机
            var printer = PrinterSettings.InstalledPrinters;  //获取本机所有打印机
            foreach (string p in printer)
            {
                PrinterDto printerEntity = new PrinterDto();
                printerEntity.PrinterName = p;
                printerEntity.Status = GetPrinterStat(p);
                printerEntity.PrintJobs = GetAllPrintJobs(p);
                if (p == defaultPrinter)
                {
                    printerEntity.IsDefault = true;
                }
                printerEntities.Add(printerEntity);
            }
            return printerEntities;
        }

        public static int GetAllPrintJobs(string name)//获取打印机当前任务队列数
        {
            LocalPrintServer localPrintServer = new LocalPrintServer();
            PrintQueue pq = localPrintServer.GetPrintQueue(name); //电脑打印机的名字
            pq.Refresh();
            PrintJobInfoCollection allPrintJobs = pq.GetPrintJobInfoCollection();
            //foreach (PrintSystemJobInfo printJob in allPrintJobs)
            //{
            //    printJob.Cancel();//取消打印任务
            //}
            return allPrintJobs.Count();
        }


        /// <summary>
        /// 获取打印机的当前状态 ///打印机状态  1其他  2未知  3空闲  4正在打印  5预热  6停止打印  7打印中  8离线
        /// </summary>
        /// <param name="PrinterDevice">打印机设备名称</param>
        /// <returns>打印机状态</returns>
        private static int GetPrinterStat(string PrinterDevice)
        {
            int ret = 0;
            string path = @"win32_printer.DeviceId='" + PrinterDevice + "'";
            ManagementObject printer = new ManagementObject(path);
            printer.Get();
            ret = Convert.ToInt32(printer.Properties["PrinterStatus"].Value);
            return ret;
        }

    }
}
